package com.ldc.common.mvvm;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.ldc.common.exception.CommonException;
import com.ldc.common.utils.ActivityUtils;

public abstract class BaseActivity<VB extends ViewBinding> extends AppCompatActivity {
    protected final String TAG = String.format("[%s]", getClass().getName());
    protected VB viewBinding;

    /**
     * 消息处理
     */
    private final Handler.Callback callback = this::handleMessage;
    /**
     * 消息队列
     */
    private final Handler handler = new Handler(callback);

    public Handler getHandler() {
        return handler;
    }

    protected abstract VB initViewBinding();

    protected VB loadViewBinding() {
        // 加载ViewBinding
        return initViewBinding();
    }


    protected abstract void main(Bundle savedInstanceState);


    protected boolean handleMessage(Message msg) {
        // 消息处理
        return false;
    }

    protected void handleError(CommonException exception) {
        // 处理异常消息
        Log.e(TAG, String.format("handleError: %s", exception.getMessage()), exception);
    }

    @Override
    protected void onStart() {
        super.onStart();
        ActivityUtils.addActivity(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            viewBinding = loadViewBinding();
            setContentView(viewBinding.getRoot());
            main(savedInstanceState);
        } catch (CommonException exception) {
            handleError(exception);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewBinding = null;
        handler.removeCallbacksAndMessages(null);
        ActivityUtils.remove(this);
    }
}
